<template>
  <div class="new-connection">
    <el-card shadow="hover">
      <el-form>
        <el-form-item v-for="param in params" :key="param.name" :label="param.name">
          <el-input :readonly="creating" v-model="param.value"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="buttons">
            <el-button size="medium" style="margin-left: auto;" @click="reset" :disabled="creating">重置参数</el-button>
            <el-button size="medium" style="margin-left: 20px;" type="primary" @click="create"
              :loading="creating">创建连接</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import api from '@/api'
export default {
  props: {},
  components: {},
  data() {
    return {
      params: [],
      creating: false
    }
  },
  computed: {
    ...mapGetters({
      defaultParams: 'global/getDefaultParams',
      connections: 'global/getConnections'
    })
  },
  watch: {
    defaultParams: {
      handler: function (newVal) {
        this.params = JSON.parse(JSON.stringify(newVal))
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    async refresh() {
      const resp = await api.connection.getAllConnection()
      if (resp.ok) {
        this.setConnections(resp.data)
      } else {
        this.$message({ message: resp.message, type: 'error', duration: 1500 })
      }
    },
    reset() {
      this.params = JSON.parse(JSON.stringify(this.defaultParams))
    },
    async create() {
      this.creating = true
      const resp = await api.connection.createConnection(this.params)
      if (resp.ok) {
        this.$message({ message: '创建成功', type: 'info', duration: 1000 })
        this.creating = false
        await this.refresh()
      } else {
        this.$message({ message: resp.message, type: 'error', duration: 1500 })
        this.creating = false
      }
    },
    ...mapActions({
      setConnections: 'global/setConnections'
    })
  },
  beforeCreate() { },
  created() { },
  beforeDestroy() { },
  destroyed() { }
}
</script>
<style lang="scss" scoped>
@use '../../../assets/scss/var.scss' as *;

.new-connection {
  padding: 16px;

  .buttons {
    width: 100%;
    display: flex;
    flex-direction: row;
  }

  @include useTheme {
    background-color: getVar('background-color');
  }
}
</style>